<template>
  <a :url="exportUrl" @click="exports">
    <!-- <slot />-->
    <el-button :loading="loading" class="filter-item" type="primary"><i class="fa fa-download"/> {{ text }}</el-button>
  </a>
</template>
<script>
import axios from 'axios'
import { getToken } from '@/utils/auth'
/* eslint-disable vue/require-default-prop,no-undef */
export default {
  name: 'ExportButton',
  props: {
    href: String,
    url: String,
    name: String,
    params: Object
  },
  data() {
    return {
      api: '',
      loading: false,
      text: '导出'
    }
  },
  computed: {
    exportUrl() {
      return this.url
      // this.export(url)
      // return process.env.BASE_API.substring(0, process.env.BASE_API.length - 5) + this.href
    }
  },
  methods: {
    exports() {
      const names = this.name
      this.loading = true
      this.text = '导出中..'
      var that = this
      axios.post(process.env.BASE_API.substring(0, process.env.BASE_API.length - 5) + this.url, this.params, {
        headers: {
          // 'Content-Type': 'application/x-www-form-urlencoded', // 请求的数据类型为form data格式
          'Content-Type': 'application/json',
          'X-Litemall-Admin-Token': getToken()
        },
        'responseType': 'blob' // 设置响应的数据类型为一个包含二进制数据的 Blob 对象，必须设置！！！
      }).then(function(response) {
        const blob = new Blob([response.data])
        const fileName = names + '.xls'
        const linkNode = document.createElement('a')
        linkNode.download = fileName // a标签的download属性规定下载文件的名称
        linkNode.style.display = 'none'
        linkNode.href = URL.createObjectURL(blob) // 生成一个Blob URL
        document.body.appendChild(linkNode)
        linkNode.click() // 模拟在按钮上的一次鼠标单击
        URL.revokeObjectURL(linkNode.href) // 释放URL 对象
        document.body.removeChild(linkNode)
        that.loading = false
        that.text = '导出'
      }).catch(function(error) {
        console.log(error)
        that.loading = false
        that.text = '导出'
      })
    },
    parseParams(data, isPrefix) {
      isPrefix = isPrefix || false
      const prefix = isPrefix ? '?' : ''
      const _result = []
      for (const key in data) {
        const value = data[key]
        // 去掉为空的参数
        if (['', undefined, null].includes(value)) {
          continue
        }
        if (value.constructor === Array) {
          value.forEach(_value => {
            _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
          })
        } else {
          _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
        }
      }
      return _result.length ? prefix + _result.join('&') : ''
    }
  }
}
</script>
